import React, {useCallback, useState, memo} from 'react';
import {View, StyleSheet, Text, ScrollView} from 'react-native';
import LazyloadImg from '../../base/LazyloadImg';
import {roundingFn} from '../../../utils/base';
import RenderPagination from '../../base/RenderPagination';
const styles = StyleSheet.create({
  swiperBox: {
    height: 300,
    width: '100%',
    backgroundColor: 'rgba(0,0,0,0)',
  },
  wrapper: {
    height: 300,
  },
  swiperItem: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
    height: 300,
    padding: 0,
    width: '100%',
  },
  img: {
    width: '100%',
    height: '100%',
  },
  scrollViewStyle: {
    width: '300%',
    height: '100%',
    backgroundColor: '#444',
  },
});

const ProductDetailSwiper = props => {
  const {list} = props;
  const [wh, setWh] = useState({width: 375, height: 300});
  const [activeIndex, setActiveIndex] = useState(0);
  const onLayout = useCallback(e => {
    setWh({
      width: e.nativeEvent.layout.width,
      height: e.nativeEvent.layout.height,
    });
  }, []);
  const onMomentumScrollEnd = useCallback(
    e => {
      const offsetX = e.nativeEvent.contentOffset.x;
      const page = roundingFn(offsetX / wh.width);
      setActiveIndex(page);
    },
    [wh],
  );
  return (
    <View style={styles.swiperBox} onLayout={onLayout}>
      <RenderScrollView
        list={list}
        onMomentumScrollEnd={onMomentumScrollEnd}
        wh={wh}
      />
      <RenderPagination list={list} active={activeIndex} />
    </View>
  );
};

const RenderScrollView = memo(({list, onMomentumScrollEnd, wh}) => {
  return (
    <ScrollView
      horizontal
      showsHorizontalScrollIndicator={false}
      pagingEnabled={true}
      onMomentumScrollEnd={onMomentumScrollEnd}
      contentContainerStyle={[
        styles.scrollViewStyle,
        {width: wh.width * list.length},
      ]}>
      {list.map((item, index) => {
        item.replace(/^http:/, 'https:');
        return (
          <View style={styles.swiperItem} key={item}>
            <LazyloadImg style={styles.img} source={{uri: item}} />
          </View>
        );
      })}
    </ScrollView>
  );
});

export default ProductDetailSwiper;
